﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using Comsenz.UCenter.Client.API.DL;
using Lbb.Data;

namespace Comsenz.UCenter.Client.API.DAL
{
    public class UCenterMemberRepository : RepositoryBase<UCenterMember>
    {
        public UCenterMemberRepository(UCenterDBDataContext db)
            : base(db)
        {

        }

        #region Get
        public UCenterMember Get(Guid? id)
        {
            return id.HasValue ? Get(d => d.UserId == id.Value) : null;
        }

        public UCenterMember Get(int? id)
        {
            return id.HasValue && id > 0 ? Get(d => d.UcUId == id.Value) : null;
        }
        #endregion Get

        public IQueryable<UCenterMember> Find(IEnumerable<Guid> userId = null, IEnumerable<int> ucUid = null)
        {
            var data = GetAll();

            if (userId != null && (userId = userId.Where(d => d != Guid.Empty).ToList()).Count() > 0) data = data.Where(d => userId.Contains(d.UserId));

            if (ucUid != null && (ucUid = ucUid.Where(d => d > 0)).Count() > 0) data = data.Where(d => ucUid.Contains(d.UcUId));

            return data;
        }

        public override void Update(UCenterMember obj)
        {
            CheckArg(obj);

            var old = Get(obj.UserId);
            if (old == null)
            {
                if (obj.UserId == Guid.Empty) return;
                Add(obj);
            }
            else
            {
                try
                {
                    Table.Attach(obj, old);
                }
                catch (InvalidOperationException)
                {
                    DB.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
                }
            }
        }
    }
}
